package com.zkc.zblog.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkc.zblog.exception.ErrorCode;
import com.zkc.zblog.exception.GotripException;
import com.zkc.zblog.mapper.ZblogUsermapper;
import com.zkc.zblog.entity.ZblogUser;
import com.zkc.zblog.md5.DigestUtil;
import com.zkc.zblog.redis.RedisUtils;
import com.zkc.zblog.redis.Token;
import com.zkc.zblog.service.ZblogUserService;
import com.zkc.zblog.service.Email;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * (ZblogUser)表服务实现类
 * @author zkc
 * @since 2019-08-10 10:04:28
 */
@Service("zblogUserService")
public class ZblogUserServiceImpl extends ServiceImpl<ZblogUsermapper, ZblogUser> implements ZblogUserService {

    @Resource
    ZblogUsermapper zblogUsermapper;

    @Resource
    RedisUtils redisUtils;
    @Resource
    Token token;

    @Resource
    Email email;



    @Override
    public ZblogUser login(String ucode, String upassword) throws Exception{
        // 输入的 用户名或密码为空 错误
        if(StringUtils.isEmpty(ucode)){
            throw new GotripException("账号为空", ErrorCode.AUTH_PARAMETER_ERROR);
        }
        //根据用户账号查询 将用户信息全部查询出来
        ZblogUser zblogUser=zblogUsermapper.selectlogin(ucode);
        if(StringUtils.isEmpty(zblogUser)){
            throw new GotripException("用户不存在", ErrorCode.AUTH_ACTIVATE_FAILED);   //用户不存在
        }
        if(!upassword.equals(zblogUser.getUpassword())){
            throw new GotripException("密码错误", ErrorCode.AUTH_AUTHENTICATION_FAILED);   //密码错误
        }
        return zblogUser;
    }
    @Override
    public String registered(String ucode) throws Exception{
        if(!validEmail(ucode)){
            throw new GotripException("邮箱格式错误", ErrorCode.AUTH_REPLACEMENT_FAILED);
        }
        //根据用户账号查询 将用户信息全部查询出来   判断用户是否存在
        ZblogUser User= zblogUsermapper.selectlogin(ucode);//用户账号进行加密在  查询
        //判断账号是否已经创建
        if(!StringUtils.isEmpty(User)){
            throw new GotripException("账户已存在", ErrorCode.AUTH_TOKEN_INVALID);
        }
        /*验证码的reids的操作*/
        int code = DigestUtil.randomCode();//构建验证码
        email.Email(ucode,String.valueOf(code));//发送验证码
        String codestring=token.stringtoken(ucode);
        token.savecode(codestring,String.valueOf(code));//将key 和 value  保存在redis中
        return codestring;
    }
    @Override
    public void registeredcode(String uname,String ucode,String upassword,String code,String token) throws GotripException {

       /*        Object jsonString =redisUtils.get(token);//获取redis中用户的信息
        ZblogUser zblogUser = JSON.parseObject((String) jsonString,ZblogUser.class); //Json字符串转化成对象   然后在放入用户表中
        if(!zblogUser.getUname().equals(uname)){
            zblogUser.setUname(uname);//用户名 和redis 中不一致  说明用户发送验证码后   对用户名经行了修改  将修改后的用户名放入
        }else if(!zblogUser.getUcode().equals(ucode)){
            throw new GotripException("更换邮箱后请重新发送验证码", ErrorCode.BIZ_HOTEL_QUERY_HOTEL_FEATURE_FAIL);
        }else if(!zblogUser.getUpassword().equals(upassword)){
            zblogUser.setUpassword(upassword);//密码 和redis 中不一致  说明用户发送验证码后   对密码经行了修改  将修改后的密码放入
        }*/

       if(StringUtils.isEmpty(uname)){
           throw new GotripException("用户名为空", ErrorCode.BIZ_QUERY_HOTEL_DETAILS_ID_FAIL);
       }else if(StringUtils.isEmpty(ucode)){
           throw new GotripException("账号为空", ErrorCode.BIZ_QUERY_HOTEL_DETAILS_FAIL);
       }else if(!validEmail(ucode)){
           throw new GotripException("邮箱格式错误", ErrorCode.AUTH_REPLACEMENT_FAILED);
       }else if(StringUtils.isEmpty(upassword)){
           throw new GotripException("密码为空", ErrorCode.BIZ_QUERY_HOTEL_DETAILS_PASSWORD);
       }else if(StringUtils.isEmpty(code)){
           throw new GotripException("验证码为空", ErrorCode.BIZ_HOTEL_QUERY_HOTEL_FEATURE_FAIL);
       }else if(StringUtils.isEmpty(token)){
           throw new GotripException("请先发送验证码", ErrorCode.BIZ_QUERY_HOTEL_DETAILS_EMAIL);
       }
        //判断用户名是否重

        ZblogUser zblogUsers= zblogUsermapper.selectuname(uname);
        if(!StringUtils.isEmpty(zblogUsers)){
            throw new GotripException("用户名重复", ErrorCode.AUTH_ILLEGAL_USERCODE);
        }
       if(!redisUtils.exist(token)){
           throw new GotripException("验证码已过期", ErrorCode.BIZ_HOTEL_QUERY_HOTEL_FEATURE_FAIL);
       }
        String keycode=(String) redisUtils.get(token);//获取redis中的验证码
        if(!keycode.equals(code)){
            throw new GotripException("输入的验证码错误", ErrorCode.BIZ_HOTEL_QUERY_TRADE_AREA_FAIL);
        }

        ZblogUser zblogUser=new ZblogUser();
        zblogUser.setUstatus((long) 2);//设置权限  激活
        zblogUser.setUclassification((long) 2);//设置用户级别  普通用户
        /*data 转 string*/
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String datanew= format.format(new Date());
        /*string 转 long*/
        Long yids=Long.parseLong(datanew);
        zblogUser.setYids(yids);//设置外键
        zblogUser.setEmail(ucode);//设置邮箱
        zblogUser.setUsex("1");
        zblogUser.setUserdata(new Date());//创建当前时间
        zblogUser.setUname(uname);//放入用户名
        zblogUser.setUcode(ucode);//放入账号
        zblogUser.setUavatar("/imgs/moren.jpg");
        /*对用户密码经行加密*/
        zblogUser.setUpassword(DigestUtil.hmacSign(upassword));
        redisUtils.unLock(token);//删除redis中验证码
        zblogUsermapper.insertSelective(zblogUser);//数据入库
    }
    /**
    *
    * current     当前页
    * size    页大小
    * */
    @Override
    public IPage<ZblogUser> UserALL(Integer current, Integer size) throws Exception{
         QueryWrapper<ZblogUser> queue = new QueryWrapper<>();
         queue.orderByAsc("uid");
         Page<ZblogUser> page= new Page<>(current,size);
         IPage<ZblogUser> iPage=zblogUsermapper.selectPage(page,queue);
         return iPage;
    }
    @Override
    public ZblogUser UserAllUpdate(Long uid) throws Exception{
        return  zblogUsermapper.selectByPrimarykey(uid);
    }
    @Override
    public Integer UserAdd(ZblogUser zblogUser) {
        return zblogUsermapper.insertSelective(zblogUser);
    }
    /**
     * 合法E-mail地址：
     * 1. 必须包含一个并且只有一个符号“@”
     * 2. 第一个字符不得是“@”或者“.”
     * 3. 不允许出现“@.”或者.@
     * 4. 结尾不得是字符“@”或者“.”
     * 5. 允许“@”前的字符中出现“＋”
     * 6. 不允许“＋”在最前面，或者“＋@”
     */
    private boolean validEmail(String email){
        String regex="^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$"  ;
        return Pattern.compile(regex).matcher(email).find();
    }





}